/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmediaplayer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;

/**
 * A collection of AudioFile.
 * Implement methods:
 *  - Load selected file and folder selected in a dialog to add to list
 *  - Load file in a .m3u playlist file
 *  - Write a .m3u playlist file from this list
 * @author PHUOCVIET
 */
public class JSongList extends ArrayList {

    /**
     * Load file from a directory recursively
     * @param dir the directory
     * @param recurse indicate recursive or not
     * @throws IOException
     */
    public void loadFromDirectory(File dir, boolean recurse)
            throws IOException {

        if (dir.isDirectory()) {
            File[] files = dir.listFiles(new AudioFileFilter(true));
            AudioFile file = null;
            AudioFileFilter aff = new AudioFileFilter(true);

            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile() && aff.accept(files[i])) {
                    try {
                        file = AudioFileIO.read(files[i]);
                        if (file != null) {
                            this.add(file);
                        }
                    } catch (Exception e) {
                        // Do nothing.  Bad file, don't add.
                    }
                } else if (files[i].isDirectory() && recurse) {
                    loadFromDirectory(files[i], recurse);
                }
            }
        } else {
            throw new IOException("Error loading playlist from a directory: "
                    + dir.getAbsolutePath() + " is not a "
                    + "directory");
        }
    }

    /**
     * Load files listed in a .m3u playlist file
     * @param m3uFile the .m3u playlist file
     * @throws PlaylistException if bad content in playlist
     * @throws FileNotFoundException
     * @throws IOException if FileReader has IOException
     */
    public void loadFromFile(File m3uFile)
            throws PlaylistException, FileNotFoundException, IOException {

        FileReader in = new FileReader(m3uFile);
        BufferedReader reader = new BufferedReader(in);
        String str = reader.readLine();
        AudioFile file = null;

        if (!str.equals("#EXTM3U\r\n")) {
            while ((str = reader.readLine()) != null) {
                if (str.indexOf("EXTINF:") != -1) {
                    str = reader.readLine();

                    try {
                        File f = new File(str);
                        file = AudioFileIO.read(f);
                        this.add(file);
                    } catch (Exception e) {
                        // Do nothing, just don't add it
                    }
                } else {
                    throw new PlaylistException();
                }
            }
        } else {
            throw new PlaylistException();
        }

        reader.close();
        in.close();
    }

    /**
     * Write a .m3u playlist file from this list of songs
     * @param dest destination
     * @throws IOException
     */
    public void writeToFile(File dest) throws IOException {
        File m3u = dest;

        if (dest.isDirectory()) {
            m3u = new File(dest, dest.getName() + ".m3u");
        }

        FileOutputStream out = new FileOutputStream(m3u);
        PrintWriter printer = new PrintWriter(out);
        printer.print(this.toString());
        printer.close();
        out.close();
    }

    @Override
    public String toString() {
//	Collections.sort( this );
        String str = "#EXTM3U\r\n";
        Iterator it = this.iterator();
        AudioFile file = null;
        String title = new String();

        while (it.hasNext()) {
            file = (MP3File) it.next();
            str += "#EXTINF:" + ",";

            Tag tag = file.getTag();
            if (tag != null) {
                title = file.getTag().getFirst(FieldKey.TITLE);
            }

            str += title + "\r\n";
            str += file.getFile().getPath() + "\r\n";
        }

        return str;
    }
}
